#include <QCoreApplication>
#include <QFile>
#include <QDebug>
#include <memory>
#include <vector>
#include <json.h>
#include "Company.h"

using namespace std;

QByteArray readFile(const QString& text)
{
	QFile file(text);
	if (file.open(QIODevice::ReadOnly))
	{
		return file.readAll();
	}
	else
		return QByteArray();
}

vector<shared_ptr<Company>> parse(const QByteArray& data)
{
	bool ok = false;
	QtJson::JsonObject result = QtJson::parse(data, ok).toMap();
	if (!ok)
		return vector<shared_ptr<Company>>();
	else
	{
		vector<shared_ptr<Company>> vec;
		QtJson::JsonObject obj = result["showapi_res_body"].toMap();
		qDebug() << obj["contentlist"].toList().size();
		foreach(QVariant v, obj["contentlist"].toList())
		{
			shared_ptr<Company> company(new Company);
			QtJson::JsonObject map = v.toMap();
			company->setCompanyName(map["name"].toString());
			company->setCode(map["code"].toString());
			company->setPinyin(map["pinyin"].toString());
			vec.push_back(company);
		}
		return vec;
	}
}



int main(int argc, char** argv)
{
	QCoreApplication a(argc, argv);
	vector<shared_ptr<Company>> vec = parse(readFile("info.json"));
	foreach(shared_ptr<Company> p, vec)
	{
		qDebug() << "Name:" << p->companyName()
			<< "\n" << "Code:" << p->code()
			<< "\nPinyin:" << p->pinyin();
	}
	return 0;
}
